//
//  GRShopSearchViewController.m
//  YC_GRice
//
//  Created by Feng Liu on 2018/8/29.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRShopSearchViewController.h"
#import "GRStoreViewController.h"
#import "GRPayBillViewController.h"

#import "UICollectionViewLeftAlignedLayout.h"
#import "GRTopSearchReusableView.h"
#import "GRUltimateShopViewCell.h"
#import "GRTopSearchViewCell.h"
#import "GRSearchTextField.h"
#import "GRHotSearchModel.h"
#import "GRBlankSpace.h"

@interface GRShopSearchViewController () <UICollectionViewDelegateLeftAlignedLayout, GRSearchTextFieldDelegate, GRTopSearchReusableViewDelegate>
{
    CGFloat   itemHeight;
    BOOL      isShowResult;
    NSString *adcode;
}
@property (nonatomic, strong) GRSearchTextField *searchBar;
@property (nonatomic, strong) GRBlankSpace *blankSpace;
@property (nonatomic, strong) NSArray<GRHotSearchModel *> *hotList;
@property (nonatomic, strong) NSMutableArray *historyList;
@property (nonatomic, strong) NSMutableArray *storeList;

@end

@implementation GRShopSearchViewController

static NSInteger  pageIndex                      = 1;
static NSString * const topSearchCell        = @"GRTopSearchViewCell";
static NSString * const nearbyShopCell      = @"GRUltimateShopViewCell";
static NSString * const topSearchReusable = @"GRTopSearchReusableView";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
    // Uncomment the following line to preserve selection between presentations
    self.searchBar = [[GRSearchTextField alloc] initWithFrame:CGRectMake(0, 0, KscreenWidth-90, 30)];
    self.searchBar.delegate = self;
    self.navigationItem.titleView = self.searchBar;
    itemHeight       = KscreenWidth/3 + 10;

    self.collectionView.bounces             = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    // Register cell classes
    [self.collectionView registerNib:[UINib nibWithNibName:topSearchReusable bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:topSearchReusable];
    [self.collectionView registerNib:[UINib nibWithNibName:topSearchCell bundle:nil] forCellWithReuseIdentifier:topSearchCell];
    [self.collectionView registerNib:[UINib nibWithNibName:nearbyShopCell bundle:nil] forCellWithReuseIdentifier:nearbyShopCell];
    // Do any additional setup after loading the view.
    [[HistoryManager shareHistory] createATable:tableName];
    self.historyList = [[HistoryManager shareHistory] getAllHistory:tableName];
    adcode            = [GRLocationManager defaultManager].adcode ? [GRLocationManager defaultManager].adcode : @"";
    
    [self topSearch];
    [self MJRefresh];
}


/**
 获取热门搜索 */
- (void)topSearch {
    WEAKSELF
    [GRHoMeAction TopSearch:adcode completionHandler:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            weakSelf.hotList = responseObject;
            [weakSelf.collectionView reloadData];
        }else {
            [GRHUD showMessage:error.errorMsg atView:weakSelf.view];
        }
    }];
}

- (void)searchResults {
    isShowResult               = YES;
    NSDictionary *paramer = @{@"areaCode": adcode,
                                          @"pageNum" : @(pageIndex),
                                          @"pageSize" : @10,
                                          @"essential" : self.searchBar.text,
                                          @"lantitude" : @([GRLocationManager defaultManager].coordinate.latitude),
                                          @"longitude" : @([GRLocationManager defaultManager].coordinate.longitude)
                                         };
    WEAKSELF
    if (self.searchBar.isFirstResponder) {
        [self.searchBar resignFirstResponder];
    }
    [self changeSearchStatus:YES];
    [GRHUD showLoading:@"正在加载" atView:self.view];
    [GRHoMeAction storeSearchResults:paramer completionHandler:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            if (pageIndex == 1) {
                [weakSelf.storeList removeAllObjects];
            }
            [weakSelf.storeList addObjectsFromArray:responseObject];
            weakSelf.blankSpace.hidden = weakSelf.storeList.count == 0 ? NO : YES;
            [weakSelf.collectionView reloadData];
        }else {
            [error errorAlertWithUIView:weakSelf.view offsetY:0 completion:^{
                [weakSelf searchResults];
            }];
        }
        
        [GRHUD dismissHUD:weakSelf.view];
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
    }];
}

- (void)MJRefresh {
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        pageIndex = 1;
        [self searchResults];
    }];
    
    self.collectionView.mj_footer = [GRRefreshBackFooter footerWithRefreshingBlock:^{
        pageIndex += 1;
        [self searchResults];
    }];
}

#pragma Mark ------------   搜索行为   ------------------
- (void)searchAction {
    if (self.searchBar.text.length > 0) {
        [[HistoryManager shareHistory] insertHistory:self.searchBar.text AtTable:tableName];
        self.historyList = [[HistoryManager shareHistory] getAllHistory:tableName];
        [self searchResults];
    }
}

/**
 GRSearchTextFieldDelegate  */
-(void)searchTextDidChange:(UITextField *)textField {
    if (self.searchBar.text.length == 0 && isShowResult) {
        isShowResult = NO;
        self.blankSpace.hidden = YES;
        [self changeSearchStatus:NO];
        [self.collectionView reloadData];
    }
}

-(void)didClickedSearchButton:(UITextField *)textField {
    [self searchAction];
}

-(void)deleteAllHistorys {
    [self.historyList removeAllObjects];
    [self.collectionView reloadData];
}

- (void)changeSearchStatus:(BOOL)status {
    if (status) {
        if (!self.collectionView.bounces) {
            self.collectionView.bounces = status;
            self.collectionView.backgroundColor = KGMBACKGROUND_COLOR;
        }
    }else {
        self.collectionView.bounces = status;
        self.collectionView.backgroundColor = [UIColor whiteColor];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark <UICollectionViewDataSource>  <UICollectionViewDelegate>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.searchBar.text.length > 0 ? 1 : 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.searchBar.text.length == 0) {
        return section == 0 ? self.hotList.count : self.historyList.count;
    }
    return self.storeList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.searchBar.text.length > 0) {
        GRUltimateShopViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:nearbyShopCell forIndexPath:indexPath];
        cell.shopModel                     = self.storeList[indexPath.item];
        return cell;
    }else {
        GRTopSearchViewCell *cell  = [collectionView dequeueReusableCellWithReuseIdentifier:topSearchCell forIndexPath:indexPath];
        cell.textLabel.text              = indexPath.section == 0 ? [self.hotList[indexPath.item] hotName] : self.historyList[indexPath.item];
        return cell;
    }
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (self.searchBar.text.length == 0 && kind == UICollectionElementKindSectionHeader) {
        GRTopSearchReusableView *searchRv = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:topSearchReusable forIndexPath:indexPath];
        searchRv.delegate = self;
        [searchRv topTitleAtIndexPath:indexPath.section count:self.historyList.count];
        return searchRv;
    }
    return nil;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.searchBar.text.length == 0) {
        NSString *text   = indexPath.section == 0 ? [self.hotList[indexPath.item] hotName] : self.historyList[indexPath.item];
        return CGSizeMake([text adaptiveWidth:30 font:14] + 20, 30);
    }else {
        return CGSizeMake(KscreenWidth, itemHeight);
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (self.searchBar.text.length == 0) {
        if (section == 1 && self.historyList.count == 0) {
            return CGSizeMake(KscreenWidth, 110);
        }
        return CGSizeMake(KscreenWidth, 40);
    }
    return CGSizeZero;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.searchBar.text.length == 0 ? 10 : 0.f;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return self.searchBar.text.length == 0 ? UIEdgeInsetsMake(0, 15, 0, 0) : UIEdgeInsetsZero;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.searchBar.text.length == 0) {
        NSString *keyword  = indexPath.section == 0 ? [self.hotList[indexPath.item] hotName] : self.historyList[indexPath.item];
        self.searchBar.text = keyword;
        [self searchResults];
    }else {
        GRUltimateShopModel *model      = self.storeList[indexPath.item];
//        GRStoreViewController *storeVc = [[GRStoreViewController alloc] init];
//        storeVc.storeId                        = model.profileOnePayId;
        if ([GRUserBasisInfo isLogin]) {
            GRPayBillViewController *billVc  = [[GRPayBillViewController alloc] init];
            billVc.storeId                           = model.profileOnePayId;
            billVc.isValid = YES;
            [self.navigationController pushViewController:billVc animated:YES];
        }else{
            [self goToLogin];
        }

    }
}

#pragma Mark ------ 懒加载
-(NSMutableArray *)storeList {
    if (!_storeList) {
        _storeList = [NSMutableArray array];
    }
    return _storeList;
}

-(GRBlankSpace *)blankSpace {
    if (!_blankSpace) {
        _blankSpace = [GRBlankSpace loadFromNib];
        _blankSpace.frame = self.view.bounds;
        _blankSpace.contentMode = GRBlankContentModeSearchLess;
        [self.view addSubview:_blankSpace];
    }
    return _blankSpace;
}

@end
